package com.example.weather_study.util;

import android.support.v4.app.INotificationSideChannel;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtil {

    //
    public static final String URL_WEATEHER_WITH_FUTURE = "https://tianqiapi.com/api?unescape=1&version=v1&appid=71834655&appsecret=DIwH2ihM";

    public static String doGet(String urlStr){
        String result = "";
        HttpURLConnection connection = null;
        InputStreamReader inputStreamReader=null;
        BufferedReader bufferedReader=null;

        // 连接网络
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            // 从连接中读取数据
            InputStream inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String line="";
            while((line=bufferedReader.readLine())!=null){
                stringBuilder.append(line);
            }

            result = stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(connection!=null){
                connection.disconnect();
            }
            if(inputStreamReader!=null){
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;


    }

    public static String  getWeatherofCity(String city){
        String weatherUrl = URL_WEATEHER_WITH_FUTURE+ "&city=" +city;
        Log.d("fan","-----weatherUrl------"+weatherUrl);
        String weatherResult = doGet(weatherUrl);
        Log.d("fan","-----weatherResult------"+weatherResult);
        return weatherResult;
    }
}
